package com.acce.gxsc.page.registerCar;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.gxsc.common.App;
import com.acce.gxsc.common.Constants;
import com.acce.gxsc.common.QuizActivity;
import com.acce.gxsc.common.Tools;
import com.acce.gxsc.model.netBean.CarPredictionBean;
import com.acce.gxsc.model.netBean.InCarBean;
import com.acce.gxsc.model.netBean.InGoodsBean;
import com.acce.gxsc.page.inCarDetail.InCarActivity;
import com.acce.gxsc.page.registerCar.addBoxInfo.AddBoxInfoActivity;
import com.acce.gxsc.page.registerCar.addCarInfo.AddCarInfoActivity;
import com.acce.gxsc.page.registerCar.addCustomInfo.AddCustomInfoActivity;
import com.acce.gxsc.page.registerCar.addGoodsInfo.AddGoodsInfoActivity;
import com.acce.gxsc.page.registerCar.editCompanyInfo.EditCompanyInfoActivity;
import com.acce.sdk.BaseActivity;
import com.acce.sdk.base.mvp.BaseMvpFragment;
import com.acce.sdk.utils.StringUtils;
import com.acce.sdk.utils.ToastUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.acce.gxsc.common.Constants.ID_2;

/**
 * Created by huxley on 2017/5/26.
 */
public class RegisterCarFragment extends BaseMvpFragment<RegisterCarView, RegisterCarPresenter> implements RegisterCarView {

    public static final int CODE_ADD_CAR_INFO    = 1001;
    public static final int CODE_ADD_CUSTOM_INFO = 1002;
    public static final int CODE_ADD_GOODS_INFO  = 1003;
    public static final int CODE_ADD_BOX_INFO    = 1004;
    public static final int CODE_EDIT_COMPANY    = 1005;
    public static final int CODE_REGISTER_CAR    = 1006;
    LayoutInflater mInflater;

    CarPredictionBean mCarPredictionBean = new CarPredictionBean();

    View rootView;
    @Bind(R.id.tv_order_id)
    TextView     mTvOrderId;
    @Bind(R.id.tv_customer)
    TextView     mTvCustomer;
    @Bind(R.id.tv_car_info)
    TextView     mTvCarInfo;
    @Bind(R.id.tv_box_info)
    TextView     mTvBoxInfo;
    @Bind(R.id.tv_goods_info)
    TextView     mTvGoodsInfo;
    @Bind(R.id.ll_goods_list)
    LinearLayout mLlGoodsList;
    @Bind(R.id.btn_save)
    TextView     mBtnSave;
    @Bind(R.id.btn_delete)
    TextView     mBtnDelete;
    @Bind(R.id.btn_in)
    TextView     mBtnIn;
    @Bind(R.id.tv_company)
    TextView     mTvCompany;
    @Bind(R.id.tv_dilivery_type_1)
    TextView     mTvDiliveryType1;
    @Bind(R.id.tv_dilivery_type_2)
    TextView     mTvDiliveryType2;

    public static RegisterCarFragment newInstance(String pregisterKey) {
        Bundle args = new Bundle();
        RegisterCarFragment fragment = new RegisterCarFragment();
        if (pregisterKey != null) {
            args.putString("pregisterKey", pregisterKey);
        } else {
            args.putString("pregisterKey", "");
        }
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected RegisterCarPresenter createPresenter() {
        return new RegisterCarPresenter();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_register_car, container, false);
        ButterKnife.bind(this, rootView);
        init();
        setHasOptionsMenu(true);
        return rootView;
    }

    boolean isNeedFinish = false;

    private void init() {
        mInflater = LayoutInflater.from(getActivity());
        String pregisterKey = getArguments().getString("pregisterKey");
        if (!StringUtils.isEmpty(pregisterKey)) {
            mCarPredictionBean.pregisterKey = pregisterKey;
            mPresenter.loadRegisterCarDetail(pregisterKey);
            mTvOrderId.setEnabled(false);
            isNeedFinish = true;
        } else {
            mTvOrderId.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
            mTvOrderId.getPaint().setAntiAlias(true);//抗锯齿
            isNeedFinish = false;
        }
        setText();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == CODE_REGISTER_CAR) {
            mPresenter.loadRegisterCarDetail(data.getStringExtra("pregisterKey"));
            return;
        }
        switch (requestCode) {
            case CODE_ADD_CAR_INFO:
                mCarPredictionBean.plateNumX = data.getStringExtra("plateNumX");
                mCarPredictionBean.plateNumG = data.getStringExtra("plateNumG");
                mCarPredictionBean.carHangNo = data.getStringExtra("carHangNo");
                break;
            case CODE_ADD_CUSTOM_INFO:
                mCarPredictionBean.owerName = data.getStringExtra("name");
                mCarPredictionBean.contactPhone = data.getStringExtra("phone");
                break;
            case CODE_ADD_GOODS_INFO:
                InGoodsBean goodsBean = new InGoodsBean();
                goodsBean.goodsId = data.getStringExtra("goodsId");
                goodsBean.goodsType = data.getStringExtra("goodsType");
                goodsBean.goodsName = data.getStringExtra("goodsName");
                goodsBean.wrapType = data.getStringExtra("goodsPackaging");
                goodsBean.plateSum = data.getStringExtra("goodNum1");
                goodsBean.quantity = data.getStringExtra("goodNum2");
                goodsBean.itemWeight = data.getStringExtra("weight");
                goodsBean.suttle = data.getStringExtra("totalWeight");
                goodsBean.wunit = data.getStringExtra("kg");
                goodsBean.goodsRemaks = data.getStringExtra("explain");
                if (mCarPredictionBean.pregistergoods == null) {
                    mCarPredictionBean.pregistergoods = new ArrayList<>();
                }
                mCarPredictionBean.pregistergoods.add(goodsBean);
                break;
            case CODE_ADD_BOX_INFO:
                mCarPredictionBean.preContainNo = data.getStringExtra("preContainNo");
                mCarPredictionBean.preContainSize = data.getStringExtra("preContainSize");
                break;
            case CODE_EDIT_COMPANY:
                mCarPredictionBean.declareCompanyNick = data.getStringExtra("father");
                mCarPredictionBean.consignorNick = data.getStringExtra("son");
                break;
        }
        setText();
    }

    public void setText() {
        if (StringUtils.isEmpty(mCarPredictionBean.pregisterKey)) {
            mTvOrderId.setText("请选择");
        } else {
            Tools.setText(mTvOrderId, mCarPredictionBean.pregisterKey);
        }
        selectDiliveryType();
        mTvCompany.setText(Tools.getString1(mCarPredictionBean.declareCompanyNick, mCarPredictionBean.consignorNick));
        mTvCustomer.setText(Tools.getString1(mCarPredictionBean.owerName, mCarPredictionBean.contactPhone));
        mTvCarInfo.setText(Tools.getString1(mCarPredictionBean.plateNumG, mCarPredictionBean.plateNumX, mCarPredictionBean.carHangNo));
        mTvBoxInfo.setText(Tools.getString2(mCarPredictionBean.preContainNo, mCarPredictionBean.preContainSize));
        Tools.setText(mTvGoodsInfo, MessageFormat.format("-{0}-项", mCarPredictionBean.pregistergoods == null ? 0 : mCarPredictionBean.pregistergoods.size()));
        mLlGoodsList.removeAllViews();
        List<InGoodsBean> goodsList = mCarPredictionBean.pregistergoods;
        String goodsInfo = "";
        if (goodsList != null) {
            for (int i = 0; i < goodsList.size(); i++) {
                InGoodsBean goodsBean = goodsList.get(i);
                View childView = mInflater.inflate(R.layout.child_goods, mLlGoodsList, false);
                LinearLayout llGoodsRemarks= (LinearLayout) childView.findViewById(R.id.ll_goods_remarks);
                TextView tvGoodsId = (TextView) childView.findViewById(R.id.tv_goods_id);
                TextView tvGoodsType = (TextView) childView.findViewById(R.id.tv_goods_type);
                TextView tvGoodsName = (TextView) childView.findViewById(R.id.tv_goods_name);
                TextView tvGoodsPackaging = (TextView) childView.findViewById(R.id.tv_packaging);
                TextView tvGoodsNum1 = (TextView) childView.findViewById(R.id.tv_goods_num_1);
                TextView tvGoodsNum2 = (TextView) childView.findViewById(R.id.tv_goods_num_2);
                TextView tvWeight = (TextView) childView.findViewById(R.id.tv_weight);
                TextView tvTotalWeight = (TextView) childView.findViewById(R.id.tv_total_weight);
                TextView tvGoodsRemarks= (TextView) childView.findViewById(R.id.input_goods_remarks);
                tvGoodsId.setText(String.valueOf(i + 1));
                tvGoodsType.setText(goodsBean.goodsType);
                tvGoodsName.setText(goodsBean.goodsName);
                tvGoodsPackaging.setText(goodsBean.wrapType);
                tvGoodsNum1.setText(goodsBean.plateSum);
                tvGoodsNum2.setText(goodsBean.quantity);
                tvWeight.setText(goodsBean.itemWeight);
                tvTotalWeight.setText(goodsBean.suttle);
                if(StringUtils.isEmpty(goodsBean.goodsRemaks)){
                    llGoodsRemarks.setVisibility(View.GONE);
                }else{
                    tvGoodsRemarks.setText(goodsBean.goodsRemaks);
                }

                mLlGoodsList.addView(childView);
                goodsInfo = goodsInfo + goodsBean.goodsName;
                if (i != goodsList.size() - 1) {
                    goodsInfo = goodsInfo + "、";
                }
            }
        }
        mCarPredictionBean.goodsInfo = goodsInfo;
        if (StringUtils.isEmpty(mCarPredictionBean.pregisterKey)) {
            mBtnSave.setEnabled(true);
            mBtnDelete.setEnabled(false);
            mBtnSave.setBackgroundResource(R.color.white);
            mBtnDelete.setBackgroundResource(R.color.divider_dark);
        } else {
            mBtnSave.setEnabled(false);
            mBtnDelete.setEnabled(true);
            mBtnSave.setBackgroundResource(R.color.divider_dark);
            mBtnDelete.setBackgroundResource(R.color.white);
        }
    }

    @OnClick({R.id.tv_order_id, R.id.tv_clear, R.id.ll_company, R.id.ll_customer, R.id.ll_car_info, R.id.ll_box_info,
            R.id.btn_add_goods, R.id.btn_save, R.id.btn_delete, R.id.btn_in, R.id.tv_dilivery_type_1, R.id.tv_dilivery_type_2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_order_id:
                Intent registerCarIntent = new Intent(getActivity(), QuizActivity.class);
                registerCarIntent.putExtra(Constants.Key.CATEGORY_ID, ID_2);
                registerCarIntent.putExtra(Constants.Key.IS_SELECT, true);
                getActivity().startActivityForResult(registerCarIntent, CODE_REGISTER_CAR);
                break;
            case R.id.ll_company:
                Intent companyInfoIntent = new Intent(getActivity(), EditCompanyInfoActivity.class);
                getActivity().startActivityForResult(companyInfoIntent, CODE_EDIT_COMPANY);
                break;
            case R.id.ll_customer:
                Intent customInfoIntent = new Intent(getActivity(), AddCustomInfoActivity.class);
                if (!StringUtils.isEmpty(mCarPredictionBean.contactPhone)) {
                    customInfoIntent.putExtra("name", mCarPredictionBean.owerName);
                }
                if (!StringUtils.isEmpty(mCarPredictionBean.contactPhone)) {
                    customInfoIntent.putExtra("phone", mCarPredictionBean.contactPhone);
                }
                getActivity().startActivityForResult(customInfoIntent, CODE_ADD_CUSTOM_INFO);
                break;
            case R.id.ll_car_info:
                Intent carInfoIntent = new Intent(getActivity(), AddCarInfoActivity.class);
                if (!StringUtils.isEmpty(mCarPredictionBean.plateNumX)) {
                    carInfoIntent.putExtra("plateNumX", mCarPredictionBean.plateNumX);
                }
                if (!StringUtils.isEmpty(mCarPredictionBean.plateNumG)) {
                    carInfoIntent.putExtra("plateNumG", mCarPredictionBean.plateNumG);
                }
                if (!StringUtils.isEmpty(mCarPredictionBean.carHangNo)) {
                    carInfoIntent.putExtra("carHangNo", mCarPredictionBean.carHangNo);
                }
                getActivity().startActivityForResult(carInfoIntent, CODE_ADD_CAR_INFO);
                break;
            case R.id.ll_box_info:
                Intent boxInfoIntent = new Intent(getActivity(), AddBoxInfoActivity.class);
                if (!StringUtils.isEmpty(mCarPredictionBean.preContainNo)) {
                    boxInfoIntent.putExtra("preContainNo", mCarPredictionBean.preContainNo);
                }
                if (!StringUtils.isEmpty(mCarPredictionBean.preContainSize)) {
                    boxInfoIntent.putExtra("preContainSize", mCarPredictionBean.preContainSize);
                }
                getActivity().startActivityForResult(boxInfoIntent, CODE_ADD_BOX_INFO);
                break;
            case R.id.btn_add_goods:
                getActivity().startActivityForResult(new Intent(getActivity(), AddGoodsInfoActivity.class), CODE_ADD_GOODS_INFO);
                break;
            case R.id.btn_save:
                ScrollView rootView = (ScrollView) mInflater.inflate(R.layout.dialog_car_info, (ViewGroup) getActivity().findViewById(R.id.dialog));
                TextView tvCompany = ButterKnife.findById(rootView, R.id.tv_company);
                TextView tvCustomer = ButterKnife.findById(rootView, R.id.tv_customer);
                TextView tvCarInfo = ButterKnife.findById(rootView, R.id.tv_car_info);
                TextView tvBoxInfo = ButterKnife.findById(rootView, R.id.tv_box_info);
                TextView tvGoodsInfo = ButterKnife.findById(rootView, R.id.tv_goods_info);

                tvCompany.setText(Tools.getString1(mCarPredictionBean.declareCompanyNick, mCarPredictionBean.consignorNick));
                tvCustomer.setText(Tools.getString1(mCarPredictionBean.owerName, mCarPredictionBean.contactPhone));
                tvCarInfo.setText(Tools.getString1(mCarPredictionBean.plateNumX, mCarPredictionBean.plateNumG));
                tvBoxInfo.setText(Tools.getString2(mCarPredictionBean.preContainNo, mCarPredictionBean.preContainSize));
                Tools.setText(tvGoodsInfo, mCarPredictionBean.goodsInfo);
                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                final AlertDialog alertDialog = builder
                        .setTitle("是否提交报备单")
                        .setView(rootView)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mPresenter.registerCar(mCarPredictionBean);
                            }
                        }).create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
                break;
            case R.id.btn_delete:
                deleteOrder();
                break;
            case R.id.btn_in:
                inRoom();
                break;
            case R.id.tv_clear:
                mCarPredictionBean.pregistergoods = new ArrayList<>();
                mLlGoodsList.removeAllViews();
                Tools.setText(mTvGoodsInfo, "-0-项");
                break;
            case R.id.tv_dilivery_type_1:
                mCarPredictionBean.acceTemp1 = mTvDiliveryType1.getText().toString();
                selectDiliveryType();
                break;
            case R.id.tv_dilivery_type_2:
                mCarPredictionBean.acceTemp1 = mTvDiliveryType2.getText().toString();
                selectDiliveryType();
                break;
        }
    }

    private void selectDiliveryType() {
        if (StringUtils.isEmpty(mCarPredictionBean.acceTemp1)) {
            mCarPredictionBean.acceTemp1 = mTvDiliveryType1.getText().toString();
        }
        boolean b = !mTvDiliveryType1.getText().toString().equals(mCarPredictionBean.acceTemp1);
        int bgColorSelect = Tools.getColor(R.color.color_09161e);
        int bgColor = Tools.getColor(R.color.color_162329);
        int tvColorSelect = Tools.getColor(R.color.color_f2);
        int tvColor = Tools.getColor(R.color.color_525f64);
        mTvDiliveryType1.setBackgroundColor(b ? bgColor : bgColorSelect);
        mTvDiliveryType1.setTextColor(b ? tvColor : tvColorSelect);
        mTvDiliveryType1.getPaint().setFakeBoldText(!b);
        mTvDiliveryType2.setBackgroundColor(!b ? bgColor : bgColorSelect);
        mTvDiliveryType2.setTextColor(!b ? tvColor : tvColorSelect);
        mTvDiliveryType2.getPaint().setFakeBoldText(b);
    }

    private void deleteOrder() {
        if (StringUtils.isEmpty(mCarPredictionBean.pregisterKey)) {
            ToastUtils.show("未找到该报表单...");
            return;
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog alertDialog = builder
                .setTitle("提醒")
                .setMessage("是否删除报备单?")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.deleteOrder(mCarPredictionBean.pregisterKey);
                    }
                }).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    private void inRoom() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog alertDialog = builder
                .setTitle("提醒")
                .setMessage("是否提交进场单?")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mCarPredictionBean.parkArea=App.currentPlace;
                        mPresenter.inRoom(mCarPredictionBean);
                    }
                }).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    @Override
    public void inRoomSuccess(final InCarBean carBean, CarPredictionBean carPredictionBean) {
        Intent intent = new Intent(getActivity(), InCarActivity.class);
        intent.putExtra("inCarKey", carBean.inCarKey);
        intent.putExtra(Constants.Key.IS_SELECT, true);
        getActivity().startActivity(intent);
        mCarPredictionBean = new CarPredictionBean();
        setText();
    }

    @Override
    public void deleteOrderSuccess() {
        ToastUtils.show("删除成功");
        if (isNeedFinish) {
            getActivity().finish();
        } else {
            mCarPredictionBean = new CarPredictionBean();
            setText();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void showProgressDialog(String s, boolean b) {
        ((BaseActivity) getActivity()).showProgressDialog(s, b);
    }

    @Override
    public void hideProgressDialog() {
        ((BaseActivity) getActivity()).hideProgressDialog();
    }

    @Override
    public void registerCarSuccess(String datas) {
        ToastUtils.show(datas);
        Intent registerCarIntent = new Intent(getActivity(), QuizActivity.class);
        registerCarIntent.putExtra(Constants.Key.CATEGORY_ID, ID_2);
        getActivity().startActivity(registerCarIntent);
        mCarPredictionBean = new CarPredictionBean();
        setText();
    }

    @Override
    public void loadRegisterCarSuccess(CarPredictionBean pregisterInfo) {
        this.mCarPredictionBean = pregisterInfo;
        setText();
    }
}
